﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using PathTracing;

[RequireComponent(typeof(MeshFilter))]
public class TriangleProxy : ShapeProxyBase
{

    private Mesh CurrentMesh
    {
        get
        {
            return GetComponent<MeshFilter>().mesh;
        }
    }


    public List<Triangle> GetAllTriangles()
    {
        List<Triangle> triangles = new List<Triangle>();

        Matrix4x4 matrix = transform.localToWorldMatrix;
        Matrix4x4 normalMatrix = matrix.inverse.transpose;

        CurrentMesh.RecalculateNormals();

        for (int i = 0; i < CurrentMesh.triangles.Length / 3; i++)
        {
            int index_1 = CurrentMesh.triangles[3 * i];
            int index_2 = CurrentMesh.triangles[3 * i + 1];
            int index_3 = CurrentMesh.triangles[3 * i + 2];

            Triangle triangle;
            triangle.P1.Position = matrix.MultiplyPoint3x4(CurrentMesh.vertices[index_1]);
            triangle.P1.Normal = normalMatrix.MultiplyVector(CurrentMesh.normals[index_1]).normalized;
            triangle.P2.Position = matrix.MultiplyPoint3x4(CurrentMesh.vertices[index_2]);
            triangle.P2.Normal = normalMatrix.MultiplyVector(CurrentMesh.normals[index_2]).normalized;
            triangle.P3.Position = matrix.MultiplyPoint3x4(CurrentMesh.vertices[index_3]);
            triangle.P3.Normal = normalMatrix.MultiplyVector(CurrentMesh.normals[index_3]).normalized;

            triangle.EmmisionColor = new Vector3(emmisionColor.r, emmisionColor.g, emmisionColor.b) * emmisionIntensity;
            triangle.BaseColor = new Vector3(baseColor.r, baseColor.g, baseColor.b);
            triangle.ReflectFactor = Mathf.Clamp01(reflectFactor);
            triangle.Roughess = 1;

            triangles.Add(triangle);
        };

        return triangles;
    }
}
